# admin@wfh.meperia.com
# wfh_org_ad_123
path = 'log/production.log'
select_regx = /2013-05-(29)/ # (1(2|3|4):??:??)/ 
ig_regx = /(Crontask::CrontaskController)/

# Processing ProjectsController#index (for 107.10.149.234 at 2013-05-29 17:59:50) [GET]
ip_regx = /(\d{1,3}\.){3}\d{1,3}/
ctlr_regx = /\w+#[a-z_]+/
time_regx = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/
prms_regx = /\{.*\}/ #Parameters: {"action"=>"index", "controller"=>"home"}
csum_regx = /Completed in (\d+)ms/
# Completed in 1974ms (View: 1, DB: 1)

info = {}

puts "----start---"
File.open(path, 'r') do |f|
	count = 0
	req_num = 0
	while !f.eof?
		line = f.readline
		count += 1
		if (line =~ select_regx) && (line =~ ip_regx) && !(line =~ ig_regx) 
			#puts "--- === start new request ===-----"
			#p line
			req_num += 1
			ip = line.match(ip_regx).to_s
			ctlr = line.match(ctlr_regx).to_s
			time = line.match(time_regx).to_s
			begin
				line = f.readline
				params = line.match(prms_regx).to_s 
			end while params.nil? || params.empty?

			begin
				line = f.readline
				csum_time = line.match(csum_regx)
				csum_time = csum_time[1] if !csum_time.nil?
				break if !(line =~ /^\s+$/)
			end while csum_time.nil? || csum_time.empty?

			info[ip] ||= {'count' => 0}
			info[ip]['count'] += 1
			info[ip]['start_time'] = time if info[ip]['count'] == 1
			info[ip]['end_time'] = time
			info[ip]['stat'] ||=  {}
			info[ip]['stat'][ctlr] ||=  []
			info[ip]['stat'][ctlr] << [time, params, csum_time]
			#p info
			#break if req_num == 10
		end
		
		puts "Readed lines: #{count}" if (count % 100000) == 0
	end
	

	puts "==== Statistics ===="
	puts "Total number of requests: #{req_num}"
	info.each do |ip, ip_h|
		ctl = nil
		req_infos = nil
		begin	
			puts "\nIP: #{ip}:"
			puts "\tNumber of requests: #{ip_h['count']}"
			puts "\tStart time: #{ip_h['start_time']}"
			puts "\tEnd time: #{ip_h['end_time']}"
			ip_h['stat'].each do |ctl, req_infos|
				if ctl == 'SessionsController#create'
					#puts "\t\t+ Action: #{ctl}" 
					puts "\t\t+ Login info:" 
					#puts "\t\t\tNumber of request: #{req_infos.length}"
					total_csum = 0
					req_infos.each do |time, pstr, csum_t|
						total_csum += csum_t.to_i
						#if ctl == 'SessionsController#create'
							pah = eval(pstr)
							puts "\t\t\tTime: #{time} - Email: #{pah["email"]}"
							puts
						#end
					end
					#puts "\t\t\tTotal consumed time: #{total_csum} ms"
				end
			end
		rescue Exception => ex
			puts "===ERROR==="
			puts ex.message
			p ip_h[ctl]
		end
	end
end


